package com.shujia.flink.core

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend
import org.apache.flink.runtime.state.StateBackend
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer
object Demo4Checkpoint {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    // 每 20秒 开始一次 checkpoint
    env.enableCheckpointing(20000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 开启在 job 中止后仍然保留的 externalized checkpoints
    env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    //设置状态后端

    //RocksDb
    val stateBackend: StateBackend = new RocksDBStateBackend("hdfs://master:9000/data/flink_checkpoint",true)

    env.setStateBackend(stateBackend)

    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092")
    properties.setProperty("group.id", "test")

    //创建消费者
    val flinkKafkaConsumer = new FlinkKafkaConsumer[String](
      "test_topic",
      new SimpleStringSchema(),
      properties)

    flinkKafkaConsumer.setStartFromEarliest() // 尽可能从最早的记录开始

    //使用kafka source
    val kafkaDS: DataStream[String] = env.addSource(flinkKafkaConsumer)

    kafkaDS.flatMap(_.split(","))
      .map((_, 1))
      .keyBy(_._1)
      .sum(1)
      .print()


    env.execute()
    /**
      *
      * 任务失败时候重启需要增加-s  ， 从最新checkpoint的位置恢复任务
      *
      * flink run -c com.shujia.flink.core.Demo4Checkpoint -p 2 -s hdfs://master:9000/data/flink_checkpoint/e8f89588b0ff8fecfad8813fd1f388b2/chk-36  flink-1.0.jar
      *
      */


    /**
      * savepoint 手动触发checkpoint, 一般用于停机维护
      *
      *
      * flink savepoint 2468beb515c704f3924136a8e497e50c hdfs://master:9000/data/savepoint -yid
      * application_1627888653326_0004
      *
      *
      */
  }
}
